package com.wandousoushu.jiusen.ui.search

import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View.GONE
import android.view.View.VISIBLE
import android.widget.CheckBox
import android.widget.LinearLayout
import androidx.appcompat.widget.SearchView
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.flexbox.FlexboxLayoutManager
import com.wandousoushu.jiusen.MyApplication
import com.wandousoushu.jiusen.R
import com.wandousoushu.jiusen.base.MyVMBaseActivity
import com.wandousoushu.jiusen.base.VMBaseActivity
import com.wandousoushu.jiusen.booksource.constant.Theme
import com.wandousoushu.jiusen.booksource.data.entities.Book
import com.wandousoushu.jiusen.booksource.data.entities.SearchBook
import com.wandousoushu.jiusen.booksource.model.BookManager
import com.wandousoushu.jiusen.booksource.model.SearchBookManager
import com.wandousoushu.jiusen.lib.dialogs.alert
import com.wandousoushu.jiusen.lib.theme.*
import com.wandousoushu.jiusen.ui.book.read.ReadOriginActivity
import com.wandousoushu.jiusen.ui.info.BookInfoActivity
import com.wandousoushu.jiusen.ui.widget.recycler.LoadMoreView
import com.wandousoushu.jiusen.util.*
import kotlinx.android.synthetic.main.activity_book_search.*
import kotlinx.android.synthetic.main.layout_search_title_bar.*
import kotlinx.android.synthetic.main.view_search.*
import kotlinx.coroutines.launch
import org.jetbrains.anko.sdk27.listeners.onClick
import org.jetbrains.anko.startActivity


class SearchActivity : MyVMBaseActivity<SearchViewModel>(R.layout.activity_book_search, theme = Theme.Dark),
        BookAdapter.CallBack,
        HistoryKeyAdapter.CallBack,
        SearchAdapter.CallBack {

    override val viewModel: SearchViewModel
        get() = getViewModel(SearchViewModel::class.java)

    lateinit var adapter: SearchAdapter
    private lateinit var bookAdapter: BookAdapter
    private lateinit var historyKeyAdapter: HistoryKeyAdapter
    private lateinit var loadMoreView: LoadMoreView

    //private var historyData: LiveData<List<String>>? = null
    private var bookData: LiveData<List<Book>>? = null
    private var menu: Menu? = null
    private var precisionSearchMenuItem: MenuItem? = null
    private var groups = linkedSetOf<String>()

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        ll_history.setBackgroundColor(backgroundColor)
        initRecyclerView()
        initSearchView()
        initOtherView()
        initLiveData()
        initIntent()
    }

    private fun initSearchView() {
        ATH.setTint(search_view_ss, primaryTextColor)
        search_view_ss.onActionViewExpanded()
        search_view_ss.isSubmitButtonEnabled = true
        search_view_ss.queryHint = getString(R.string.search_book_key)
        search_view_ss.clearFocus()
        search_view_ss.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
            override fun onQueryTextSubmit(query: String?): Boolean {
                search_view_ss.clearFocus()
                query?.let {
                    viewModel.saveSearchKey(query)
                    viewModel.search(it)
                }
                openOrCloseHistory(false)
                return true
            }

            override fun onQueryTextChange(newText: String?): Boolean {
                if (newText.isNullOrBlank()) viewModel.stop()
                upHistory(newText)
                return false
            }
        })
        search_view_ss.setOnQueryTextFocusChangeListener { _, hasFocus ->
            if (!hasFocus && search_view_ss.query.toString().trim().isEmpty()) {
                finish()
            } else {
                openOrCloseHistory(hasFocus)
            }
        }
        openOrCloseHistory(true)
    }

    private fun initRecyclerView() {
        ATH.applyEdgeEffectColor(recycler_view)
        ATH.applyEdgeEffectColor(rv_bookshelf_search)
        ATH.applyEdgeEffectColor(rv_history_key)
        bookAdapter = BookAdapter(this, this)
        rv_bookshelf_search.layoutManager = FlexboxLayoutManager(this)
        rv_bookshelf_search.adapter = bookAdapter
        historyKeyAdapter = HistoryKeyAdapter(this, this)
        rv_history_key.layoutManager = FlexboxLayoutManager(this)
        rv_history_key.adapter = historyKeyAdapter
        adapter = SearchAdapter(this, this)
        recycler_view.layoutManager = LinearLayoutManager(this)
        recycler_view.adapter = adapter
        adapter.registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() {
            override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
                super.onItemRangeInserted(positionStart, itemCount)
                if (positionStart == 0) {
                    recycler_view.scrollToPosition(0)
                }
            }
        })
        loadMoreView = LoadMoreView(this)
        recycler_view.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                if (!recyclerView.canScrollVertically(1)) {
                    scrollToBottom()
                }
            }
        })
    }

    private fun initOtherView() {
        fb_stop.backgroundTintList =
                Selector.colorBuild()
                        .setDefaultColor(accentColor)
                        .setPressedColor(ColorUtils.darkenColor(accentColor))
                        .create()
        fb_stop.onClick {
            viewModel.stop()
            refresh_progress_bar.isAutoLoading = false
        }
        search_tv_cacel.onClick {
            viewModel.stop()
            refresh_progress_bar.isAutoLoading = false
        }
        tv_clear_history.onClick { viewModel.clearHistory() }
    }

    private fun initLiveData() {
        viewModel.searchBookLiveData.observe(this, Observer {
            upSearchItems(it)
        })
        viewModel.isSearchLiveData.observe(this, Observer {
            if (it) {
                startSearch()
            } else {
                searchFinally()
            }
        })
        BookManager.GetInstance().bookShelfByKey?.observe(this, Observer {
            if (it.isEmpty()) {
                tv_book_show.gone()
                rv_bookshelf_search.gone()
            } else {
                tv_book_show.visible()
                rv_bookshelf_search.visible()
            }
            bookAdapter.setItems(it)
        })
        SearchBookManager.GetInstance().historyKeyList?.observe(this, Observer {
            historyKeyAdapter.setItems(it)
            if (it.isEmpty()) {
                tv_clear_history.invisible()
            } else {
                tv_clear_history.visible()
            }
        })
    }

    private fun initIntent() {
        intent.getStringExtra("key")?.let {
            search_view_ss.setQuery(it, true)
        } ?: let {
            search_view_ss.requestFocus()
        }
    }

    /**
     * 滚动到底部事件
     */
    private fun scrollToBottom() {
        if (!viewModel.isLoading && viewModel.searchKey.isNotEmpty() && loadMoreView.hasMore) {
            viewModel.search("")
        }
    }

    /**
     * 打开关闭历史界面
     */
    private fun openOrCloseHistory(open: Boolean) {
        if (open) {
            upHistory(search_view_ss.query.toString())
            ll_history.visibility = VISIBLE
        } else {
            ll_history.visibility = GONE
//            tv_search_none.visible()
//            tv_book_show.gone()
//            rv_bookshelf_search.gone()
        }
    }

    /**
     * 更新搜索历史
     */
    private fun upHistory(key: String? = null) {
        BookManager.GetInstance().bookShelfByKey?.removeObservers(this)
        if (key.isNullOrBlank()) {
            tv_book_show.gone()
            rv_bookshelf_search.gone()
        } else {
//            bookData = App.db.bookDao().liveDataSearch(key)
//            bookData=MyApplication.getInstance().bookList
            BookManager.GetInstance().GetBookShelfBykey(key)
            BookManager.GetInstance().bookShelfByKey?.observe(this, Observer {
                if (it.isEmpty()) {
                    tv_book_show.gone()
                    rv_bookshelf_search.gone()
                } else {
                    tv_book_show.visible()
                    rv_bookshelf_search.visible()
                }
                bookAdapter.setItems(it)
            })
        }
        SearchBookManager.GetInstance().historyKeyList?.removeObservers(this)
        //historyData = MyApplication.getInstance().historyKeyList
//            if (key.isNullOrBlank()) {
//                MyApplication.getInstance().historyKeyList
//                //App.db.searchKeywordDao().liveDataByUsage()
//            } else {
//                App.db.searchKeywordDao().liveDataSearch(key)
//            }
        SearchBookManager.GetInstance().historyKeyList?.observe(this, Observer {
            historyKeyAdapter.setItems(it)
            if (it.isEmpty()) {
                tv_clear_history.invisible()
            } else {
                tv_clear_history.visible()
            }
        })
    }

    /**
     * 更新搜索结果
     */
    @Synchronized
    private fun upSearchItems(items: List<SearchBook>) {
        if (items.size==0){
            tv_search_none.visible()
        }else{
            tv_search_none.gone()
        }
        adapter.setItems(items)
    }

    /**
     * 开始搜索
     */
    private fun startSearch() {
        refresh_progress_bar.isAutoLoading = true
        fb_stop.visible()
    }

    /**
     * 搜索结束
     */
    private fun searchFinally() {
        refresh_progress_bar.isAutoLoading = false
        loadMoreView.startLoad()
        fb_stop.invisible()
    }

    /**
     * 显示书籍详情
     */
    @SuppressLint("InflateParams")
    override fun showBookInfo(name: String, author: String) {
        if (getPrefBoolean("isReadReader", false)) {
            viewModel.getSearchBook(name, author) { searchBook ->
                searchBook?.let {
                    startActivity<BookInfoActivity>(
                            Pair("name", it.name),
                            Pair("author", it.author)
                    )
                }
            }
        } else {
            alert(
                    titleResource = R.string.sure_origin_read_title,
                    messageResource = R.string.sure_reader_read
            ) {
                val checkBox = CheckBox(this@SearchActivity).apply {
                    setText(R.string.sure_remeber_select)
                }
                val view = LinearLayout(this@SearchActivity).apply {
                    setPadding(16.dp, 0, 16.dp, 0)
                    addView(checkBox)
                }
                customView = view
                positiveButton(R.string.yes) {
                    if (checkBox.isChecked) {
                        putPrefBoolean("isReadReader", true)
                    }
                    viewModel.getSearchBook(name, author) { searchBook ->
                        searchBook?.let {
                            startActivity<BookInfoActivity>(
                                    Pair("name", it.name),
                                    Pair("author", it.author)
                            )
                        }
                    }
                }
                negativeButton(R.string.no) {
                    viewModel.getSearchBook(name, author) { searchBook ->
                        searchBook?.let {
                            startActivity<ReadOriginActivity>(
                                    Pair("bookUrl", it.bookUrl)
                            )
                        }
                    }
                }
            }.show()
        }


//        viewModel.getSearchBook(name, author) { searchBook ->
//            searchBook?.let {
//                AlertDialog.Builder(this)
//                        .setTitle("Notice")
//                        .setMessage("Some Message")
//                        .setPositiveButton("OK") { _, _ ->
//                            // do sth
//                            }
//                            .create().show()
////                alert(
////                        titleResource = R.string.sure,
////                        messageResource = R.string.sure_del
////                ) {
////                    val checkBox = CheckBox(this@SearchActivity).apply {
////                        setText(R.string.delete_book_file)````
////                    }
////                    val view = LinearLayout(this@SearchActivity).apply {
////                        setPadding(16.dp, 0, 16.dp, 0)
////                        addView(checkBox)
////                    }
////                    customView = view
////                    positiveButton(R.string.yes) {
////                        finish()
////                    }
////                    negativeButton(R.string.no)
////                }.show()
////                startActivity<BookInfoActivity>(
////                    Pair("name", it.name),
////                    Pair("author", it.author)
////                )
//            }
//        }
    }

    /**
     * 显示书籍详情
     */
    override fun showBookInfo(book: Book) {
        startActivity<BookInfoActivity>(
                Pair("name", book.name),
                Pair("author", book.author)
        )
    }

    /**
     * 点击历史关键字
     */
    override fun searchHistory(key: String) {
        launch {
            search_view_ss.setQuery(key, true)
//            when {
//                search_view.query.toString() == key -> {
//                    search_view.setQuery(key, true)
//                }else-> {
//                search_view.setQuery(key, true)
//            }

//                withContext(IO) {
//                    App.db.bookDao().findByName(key).isEmpty() } -> {
//                    search_view.setQuery(key, true)
//                }
//                else -> {
//                    search_view.setQuery(key, false)
//                }
//            }
        }
    }
}